package npcSystem.enemies;

import levelSystem.MapLevel;
import tools.Constants;
import tools.ImageHandler;
import tools.Physics;
import tools.Rect;

public class BasicEnemy extends Enemy{

	private boolean err;
	private int minDistance;
			
	public BasicEnemy(MapLevel l) {
		this(50, 50, new Rect(), l);
	}
	public BasicEnemy(int ox, int oy, Rect c, MapLevel l) {
		super();
		
		curLevel = l;
		
		maxDeadFrames = 4;
		maxImuneTime = 3;
		maxKnockedBackTime = 3;
		health = 2;
		
		maxHealth = 2;
		
		me = new Rect(ox, oy, Constants.NPC_DEFAULT_SPRITE_WIDTH, Constants.NPC_DEFAULT_SPRITE_HEIGHT);
		cam = c;
		
		vel = 1;
		xVel = 0;
		yVel = 0;
		
		sprite = ImageHandler.loadImage("/img/enemies/pacoca.png");
		sprite = ImageHandler.addColorKey(sprite);
		
		if(sprite == null)
		{
			err = true;
		}
		
		maxFrameSkip = 4;
		minDistance = 150;
		
		if(sprite != null)
		{
			clips = new Rect[sprite.getHeight()/Constants.TILE_HEIGHT][sprite.getWidth()/Constants.TILE_WIDTH];
			
			initClips();
			setClips();
		}
		curDir = 4;
	}
	
	@Override
	public void move()
	{
		double targetX = curLevel.getMainChar().getX();
		double targetY = curLevel.getMainChar().getY();
		if(dead)
		{
			me.x += xVel;
			me.y += yVel;
		}else if(Physics.getDistance(me.x, me.y, targetX, targetY) <= minDistance && !knockedBack)
		{
			moving = true;

			if(me.y < targetY)
			{
				curDir = 4;
				yVel = +vel;
				if(me.y + yVel > targetY)
				{
					yVel = targetY - me.y;
				}
			}else if(me.y > targetY)
			{
				curDir = 3;
				yVel = -vel;
				if(me.y + yVel < targetY)
				{
					yVel = me.y - targetY;
				}
			}else
			{
				yVel = 0;
			}
			if(me.x < targetX)
			{
				curDir = 2;
				xVel = +vel;
				if(me.x + xVel > targetX)
				{
					xVel = targetX - me.x;
				}
			}else if(me.x > targetX)
			{
				curDir = 1;
				xVel = -vel;
				if(me.x + xVel < targetX)
				{
					xVel = me.x - targetX;
				}
			}else
			{
				xVel = 0;
			}
			
			me.x += xVel;
			if(me.x < 0 || me.x + me.w > curLevel.getLevelWidth() || hitWall(curLevel.getShowingWalls())) me.x -= xVel;
			

			me.y += yVel;
			if(me.y < 0 || me.y + me.h > curLevel.getLevelHeight() || hitWall(curLevel.getShowingWalls())) me.y -= yVel;
		}else moving = false;
	}
	
	@Override
	public int logic() {
		if(err)
		{
			return -1;
		}
		move();
		if(knockedBack) calcKnockedTime();
		if(imune) calcImuneTime();
		if(health <= 0)
		{
			dead = true;
		}
		if(dead)
		{
			deadFrames++;
			if(deadFrames >= maxDeadFrames)
			{
				return 1;
			}
		}
		
		return 0;
	}		
}